package it.amicosmanettone.finance.stocky;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import it.amicosmanettone.finance.stocky.adapter.ListAdapterMain;
import it.amicosmanettone.finance.stocky.archive.ArchiveManager;
import it.amicosmanettone.finance.stocky.bean.PortfolioBean;
import it.amicosmanettone.finance.stocky.util.ErrorCode;
import it.amicosmanettone.finance.stocky.util.FinanceUtil;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends SherlockActivity{

	static ListView listPortfolios = null;
	static ListAdapterMain adapter = null;

	String textOfOKBox;
	String textError;
	
	TextView textZeroPortfolios;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		
		final SharedPreferences sharedPref = PreferenceManager
				.getDefaultSharedPreferences(this);
		
		int START_APP = sharedPref.getInt("start_app", 1);
		if (Integer.valueOf(START_APP) == 1) {
			
			new Handler().postDelayed(new Runnable() {
			    public void run() {
			    	
			    	Log.v("POP UP MAIN", "MOSTRO");
			    	initiatePopupWindow();
			    	
			    	Editor EDIT = sharedPref.edit();
					EDIT.putInt("start_app", 0).commit();
					
			    }
			}, 100);

		}
		
		setContentView(R.layout.activity_main);
		
		
		
		Typeface monster = Typeface.createFromAsset(getAssets(), "monster.ttf");
		TextView textTitle = (TextView) findViewById(R.id.textTitleMain);
		
		textTitle.setTypeface(monster);
		textTitle.refreshDrawableState();

		ArchiveManager.retrieveAllPortfolios(getApplicationContext());

		int NUMBER = FinanceUtil.getAllPortfolio().size();

		String toastNOPortfolio = getText(R.string.mainRefreshNOPortfolios)
				.toString();
		String toastYESThirst = getText(R.string.mainRefreshPortfoliosYESThirst)
				.toString();
		String toastYESSecond = getText(R.string.mainRefreshPortfoliosYESSecond)
				.toString();
		
		this.textZeroPortfolios = (TextView) findViewById(R.id.textZeroPortfolios);

		if (NUMBER <= 0) {

			textZeroPortfolios.setText(toastNOPortfolio);

		} else if (NUMBER > 0) {

			Toast.makeText(this,
					toastYESThirst + " " + NUMBER + " " + toastYESSecond,
					Toast.LENGTH_SHORT).show();

		}

		listPortfolios = (ListView) findViewById(R.id.listPortfolios);
		registerForContextMenu(listPortfolios);

		adapter = new ListAdapterMain(getApplicationContext(),
				R.layout.row_main);

		listPortfolios.setAdapter(adapter);
		Log.v("ACTIVITY", "Invoco ADDALL");

		adapter.addAll(FinanceUtil.getAllPortfolio());

		Log.e("ACTIVITY", "RECUPERO " + NUMBER + " PORTAFOGLI");

		listPortfolios.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// selected item
				String nameOfPortfolio = FinanceUtil.getAllPortfolio()
						.get(position).getPortfolioName();

				Intent i = new Intent(getApplicationContext(),
						StockPortfolioActivity.class);

				i.putExtra("nameOfPortfolio", nameOfPortfolio);
				i.putExtra("POSITION", position);
				startActivity(i);

			}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		getSupportMenuInflater().inflate(R.menu.main, menu);
		if(FinanceUtil.IS_LITE_APP_VERSION == false){
			
			menu.removeItem(R.id.action_premium);
			
		}
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case android.R.id.home:
			onBackPressed();
			return true;

		case R.id.action_portfolio:

			NewPortfolio();

			return true;

		case R.id.action_refresh:

			boolean isUpdated = FinanceUtil.updateAllPortfolios();
			if (isUpdated) {

				String dialogText = getText(R.string.mainRefreshPortfolios)
						.toString();
				String toastNOPortfolio = getText(
						R.string.mainRefreshNOPortfolios).toString();
				String toastYESThirst = getText(
						R.string.mainRefreshPortfoliosYESThirst).toString();
				String toastYESSecond = getText(
						R.string.mainRefreshPortfoliosYESSecond).toString();

				ProgressDialog mProgressDialog = new ProgressDialog(this);
				mProgressDialog.setMessage(dialogText);
				mProgressDialog.show();

				int NUM = FinanceUtil.getAllPortfolio().size();
				
				if (NUM <= 0) {

					textZeroPortfolios.setText(toastNOPortfolio);

				}else {
					
					textZeroPortfolios.setText("");
					
				}

				adapter.clear();
				adapter.addAll(FinanceUtil.getAllPortfolio());

				Log.v("ACTIVITY", "RECUPERO " + NUM + " PORTAFOGLI");

				mProgressDialog.dismiss();

				if (NUM <= 0) {

					Toast.makeText(this, toastNOPortfolio, Toast.LENGTH_SHORT)
							.show();

				} else if (NUM > 0) {

					Toast.makeText(this,
							toastYESThirst + " " + NUM + " " + toastYESSecond,
							Toast.LENGTH_SHORT).show();

				}

			}

			return true;

		case R.id.action_share:

			String shareMessage = getString(R.string.action_share_message_main);
			String shareTitle = getString(R.string.action_share_title_main);
			Intent sharingIntent = new Intent(Intent.ACTION_SEND);
			sharingIntent.setType("text/plain");
			sharingIntent
					.putExtra(
							Intent.EXTRA_TEXT,
							"https://play.google.com/store/apps/details?id=it.amicosmanettone.finance.stocky");
			sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
					shareMessage);
			startActivity(Intent.createChooser(sharingIntent, shareTitle));

			return true;
			
		case R.id.action_premium:

			Toast.makeText(this, "PREMIUM", Toast.LENGTH_SHORT).show();

			return true;

		case R.id.action_settings:

			Intent settingsIntent = new Intent(this, SettingsActivity.class);
			startActivity(settingsIntent);

			return true;

		case R.id.action_information:
			
			Intent informationIntent = new Intent(this, InformationActivity.class);
			startActivity(informationIntent);

			return true;

		case R.id.action_reportBug:

			Intent reportBug = new Intent(this, MailActivity.class);
			reportBug.putExtra("nameOfActivity", "reportBug");
			startActivity(reportBug);

			return true;

		case R.id.action_advice:

			Intent reportAdvice = new Intent(this, MailActivity.class);
			reportAdvice.putExtra("nameOfActivity", "reportAdvice");
			startActivity(reportAdvice);

			return true;

		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed() {
		String text = getText(R.string.mainExitText).toString();
		String yes = getText(R.string.mainExitYES).toString();
		String no = getText(R.string.mainExitNO).toString();
		new AlertDialog.Builder(this).setMessage(text).setCancelable(false)
				.setPositiveButton(yes, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				}).setNegativeButton(no, null).show();
	}
	
	

	public void NewPortfolio() {

		String title = getText(R.string.mainNewPortfolioTitle).toString();
		String text = getText(R.string.mainNewPortfolioText).toString();
		String buttonY = getText(R.string.mainNewPortfolioYES).toString();
		String buttonN = getText(R.string.mainNewPortfolioNO).toString();

		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title);
		alert.setMessage(text);
		alert.setCancelable(false);

		final EditText namePortfolio = new EditText(this);
		alert.setView(namePortfolio);

		alert.setPositiveButton(buttonY, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				String nameOfPortfolio = namePortfolio.getEditableText()
						.toString();
				if (nameOfPortfolio.isEmpty()) {
					error("WRITE");
				}else if (nameOfPortfolio.length() > 50) {
					error("ERROR_LENGHT");
				}else if (!nameOfPortfolio.isEmpty()) {
					String isCreated = FinanceUtil
							.createNewPortfolio(nameOfPortfolio);

					Log.v("ACTIVITY", "portfolio created " + isCreated);
					if (isCreated.equals(ErrorCode.NO_ERROR)) {
						Log.v("SALVO PORT", "Sto per salvare ");
						String STORE = ArchiveManager
								.storeAllPortfolios(getApplicationContext());
						if (STORE.equals(ErrorCode.NO_ERROR)) {
							Log.v("SALVO PORT", "Mostro OK");
							okBox(nameOfPortfolio, "NEW PORTFOLIO");
						} else {
							Log.v("SALVO PORT", "ERRORE");
						}

					} else if (isCreated.equals(ErrorCode.ERR_EXIST)) {
						error("EXIST");
					} else if (isCreated.equals(ErrorCode.ERR_NO_PREMIUM)) {
						errorNoPremium();
					}
				}

			} // End of onClick
		}); // End of alert.setPositiveButton

		alert.setNegativeButton(buttonN, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				dialog.cancel();
			}

		}); // End of alert.setNegativeButton

		AlertDialog alertDialog = alert.create();
		alertDialog.show();

	}

	public void okBox(String nameOfPortfolio, String ACTION) {

		if (ACTION.equals("NEW PORTFOLIO")) {

			this.textOfOKBox = getText(R.string.mainNewPortfolioOK).toString();

		} else if (ACTION.equals("NEW PORTFOLIO NAME")) {

			this.textOfOKBox = getText(R.string.mainModifyPortfolioOK)
					.toString();

		} else if (ACTION.equals("DELETE PORTFOLIO")) {

			this.textOfOKBox = getText(R.string.mainDeletePortfolioOK)
					.toString();

		}

		final String OKButton = getText(R.string.mainNewPortfolioOKButton)
				.toString();

		new AlertDialog.Builder(this)
				.setMessage(textOfOKBox + " " + nameOfPortfolio)

				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								
								String toastNOPortfolio = getText(
										R.string.mainRefreshNOPortfolios).toString();
								
								int NUM = FinanceUtil.getAllPortfolio().size();
								
								if (NUM <= 0) {

									textZeroPortfolios.setText(toastNOPortfolio);

								}else {
									
									textZeroPortfolios.setText("");
									
								}
								
								adapter.clear();
								adapter.addAll(FinanceUtil.getAllPortfolio());

							}
						}).show();

	}

	public void errorNoPremium() {

		String textNoPremium = getText(R.string.mainNewPortfolioErrorNoPremium)
				.toString();
		String OKButton = getText(R.string.mainNewPortfolioOKButton).toString();

		new AlertDialog.Builder(this)
				.setMessage(textNoPremium)
				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int whichButton) {

							}
						}).show();

	}

	public void error(String ACTION) {

		
		
		if(ACTION.equals("EXIST")){
			
			this.textError = getText(R.string.mainNewPortfolioErrorExist).toString();
			
		}else if(ACTION.equals("WRITE")){
			
			this.textError = getText(R.string.mainNewPortfolioErrorWrite).toString();
			
		}else if(ACTION.equals("ERROR_LENGHT")){
			
			this.textError = getText(R.string.mainNewPortfolioErrorLenght).toString();
			
		}
		
		String OKButton = getText(R.string.mainNewPortfolioOKButton).toString();

		new AlertDialog.Builder(this)
				.setMessage(textError)
				.setCancelable(false)
				.setNeutralButton(OKButton,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog,
									int whichButton) {

							}
						}).show();

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
		String nameOfPortfolio = FinanceUtil.getAllPortfolio()
				.get(info.position).getPortfolioName();

		String modifyPortfolio = getText(R.string.mainContextMenuModify)
				.toString();
		String deletePortfolio = getText(R.string.mainContextMenuDelete)
				.toString();

		menu.setHeaderTitle(nameOfPortfolio);
		menu.add(modifyPortfolio);
		menu.add(deletePortfolio);

	}

	public boolean onContextItemSelected(android.view.MenuItem item) {

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		PortfolioBean detailPortfolio = FinanceUtil.getAllPortfolio().get(
				info.position);

		String modifyPortfolio = getText(R.string.mainContextMenuModify)
				.toString();
		String deletePortfolio = getText(R.string.mainContextMenuDelete)
				.toString();
		String error = getText(R.string.mainContextMenuError).toString();

		String nameOfPortfolio = detailPortfolio.getPortfolioName();

		if (item.getTitle().equals(deletePortfolio)) {

			deleteConfirm(nameOfPortfolio);

		} else if (item.getTitle().equals(modifyPortfolio)) {

			modifyName(detailPortfolio);

		} else {

			Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
			return false;

		}

		return true;
	}

	public void modifyName(final PortfolioBean detailPortfolio) {

		String title = getText(R.string.mainModifyPortfolioTitle).toString();
		String text = getText(R.string.mainModifyPortfolioText).toString();
		String buttonY = getText(R.string.mainModifyPortfolioYES).toString();
		String buttonN = getText(R.string.mainModifyPortfolioNO).toString();

		String NamePortfolio = detailPortfolio.getPortfolioName();

		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title + " " + NamePortfolio);
		alert.setMessage(text);
		alert.setCancelable(false);

		final EditText newNamePortfolio = new EditText(this);
		newNamePortfolio.setText(NamePortfolio);
		alert.setView(newNamePortfolio);

		alert.setPositiveButton(buttonY, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				String newNameOfPortfolio = newNamePortfolio.getEditableText()
						.toString();

				if (newNameOfPortfolio.isEmpty()) {
					error("WRITE");
				} else if (!newNameOfPortfolio.isEmpty()) {

					FinanceUtil.changePortfolioName(detailPortfolio,
							newNameOfPortfolio);
					String STORE = ArchiveManager
							.storeAllPortfolios(getApplicationContext());
					if (STORE.equals(ErrorCode.NO_ERROR)) {
						Log.v("SALVO PORT", "Mostro OK");
						okBox(newNameOfPortfolio, "NEW PORTFOLIO NAME");
					} else {
						Log.v("SALVO PORT", "ERRORE");
					}

				}

			} // End of onClick
		}); // End of alert.setPositiveButton

		alert.setNegativeButton(buttonN, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				dialog.cancel();
			}

		}); // End of alert.setNegativeButton

		AlertDialog alertDialog = alert.create();
		alertDialog.show();

	}//End modifyName

	public void deleteConfirm(final String nameOfPortfolio) {

		String title = getText(R.string.mainDeletePortfolioTitle).toString();
		String text = getText(R.string.mainDeletePortfolioText).toString();
		String buttonY = getText(R.string.mainDeletePortfolioYES).toString();
		String buttonN = getText(R.string.mainDeletePortfolioNO).toString();

		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setTitle(title + " " + nameOfPortfolio);
		alert.setMessage(text);
		alert.setCancelable(false);

		alert.setPositiveButton(buttonY, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				boolean isDeleted = FinanceUtil
						.deletePortfolio(nameOfPortfolio);

				String STORE = ArchiveManager
						.storeAllPortfolios(getApplicationContext());

				if (STORE.equals(ErrorCode.NO_ERROR)) {
					okBox(nameOfPortfolio, "DELETE PORTFOLIO");
					Log.v("SALVO PORT", "Mostro OK");
				} else {
					
					Log.v("SALVO PORT", "ERRORE");
				}

			}// End onClick
		});// End positiveButton

		alert.setNegativeButton(buttonN, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

				dialog.cancel();
			}

		}); // End of NegativeButton

		AlertDialog alertDialog = alert.create();
		alertDialog.show();

	}
	
	private PopupWindow pwindo;

	private void initiatePopupWindow() {
		try {
			Log.e("POP UP", "Mostro");
			String text = getText(R.string.mainPopupText).toString();
			
			LayoutInflater inflater = (LayoutInflater) MainActivity.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.main_popup,
					(ViewGroup) findViewById(R.id.popup_element));
			
			int WIDTH = 600;
			int HEIGHT = 650;
			pwindo = new PopupWindow(layout, WIDTH, HEIGHT, true);
			pwindo.setHeight(HEIGHT);
			pwindo.setWidth(WIDTH);
			pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);

			Button btnClosePopup = (Button) layout
					.findViewById(R.id.btn_close_popup);
			
			btnClosePopup.setOnClickListener(cancel_button_click_listener);
			
			Typeface robotoThin = Typeface.createFromAsset(getAssets(),
					"Roboto-Bold.ttf");
			
			
			TextView textWelcome = (TextView) layout.findViewById(R.id.welcomeText);
			
			textWelcome.setTypeface(robotoThin);
			textWelcome.refreshDrawableState();
			textWelcome.setText(text);
			
			

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private OnClickListener cancel_button_click_listener = new OnClickListener() {
		public void onClick(View v) {
			pwindo.dismiss();

		}
	};

}// End class
